<template>
  <div class="video-container">
    <div class="video-container-left">
      <h3>
        {{ videoTitle }}
        <span class="onlineNum">{{ isLogin ? onlineNumber : "" }}</span>
      </h3>
      <h5>{{ videoIntro }}</h5>
      <div ref="dplayer" id="dplayer" class="dplayer-container"></div>
      <!--<div class="video-info-container">
        <el-row :gutter="5">
          <el-col :span="4" :offset="0">同时在看</el-col>
          <el-col :span="4" :offset="0">已装填多少弹幕</el-col>
          <el-col :span="4" :offset="0">点赞数量</el-col>
          <el-col :span="4" :offset="0">收藏数量</el-col>
          <el-col :span="4" :offset="0">评论数量</el-col>
        </el-row>
      </div> -->
      <div class="comment-conatiner">
        <div class="input-comment-container">
          <el-row :gutter="20">
            <el-col :span="2" :offset="0">
              <el-image
                class="avatar-image"
                :src="avatar"
                fit="fill"
                :lazy="true"
              ></el-image>
            </el-col>
            <el-col :span="18" :offset="0">
              <el-input
                rows="3"
                type="textarea"
                placeholder="发一条低调又不失礼貌的评论吧~"
                resize="none"
                v-model="commentContent"
              >
              </el-input>
            </el-col>
            <el-col :span="2" :offset="0">
              <el-button
                class="send-commit-btn"
                type="primary"
                size="default"
                @click="sendComment"
                >发表评论</el-button
              >
            </el-col>
          </el-row>
          <el-divider></el-divider>
        </div>
        <div
          class="comment-list-container"
          v-for="commentItem in commentList"
          :key="commentItem.id"
        >
          <el-row class="top-comment-container" :gutter="20">
            <el-col :span="2" :offset="0">
              <el-image
                class="avatar-image"
                :src="commentItem.avatar"
                fit="fill"
              ></el-image>
            </el-col>
            <el-col :span="18" :offset="0">
              <div class="commentItem-nickname">
                {{ commentItem.nickname }}
                <el-button
                  type="primary"
                  size="mini"
                  @click="openInputDailog(commentItem.id)"
                  >回复</el-button
                >
              </div>
              <div class="commentItem-content">{{ commentItem.content }}</div>
              <div>
                <div class="commentItem-time">{{ commentItem.time }}</div>
              </div>
            </el-col>
          </el-row>
          <el-row
            v-for="childComment in commentItem.child"
            :key="childComment.id"
            :gutter="20"
            style="margin-top: 20px"
          >
            <el-col :span="1" :offset="1">
              <el-image
                class="avatar-image"
                :src="childComment.avatar"
                fit="fill"
                style="width: 40px; height: 40px"
              ></el-image>
            </el-col>
            <el-col :span="18" :offset="0">
              <div class="commentItem-nickname">
                {{
                  childComment.userId == authorId
                    ? "up主  回复"
                    : childComment.nickname
                }}
              </div>
              <div class="commentItem-content">{{ childComment.content }}</div>
              <div>
                <div class="commentItem-time">{{ childComment.time }}</div>
              </div>
            </el-col>
          </el-row>
          <el-divider></el-divider>
        </div>
      </div>
    </div>
    <div class="video-container-right">
      <div class="author-container">
        <div class="author-container-left">
          <el-image
            class="author-avatar"
            :src="author.avatar"
            fit="fill"
            :lazy="true"
          ></el-image>
        </div>
        <div class="author-container-right">
          <div class="author-container-top">
            <h3>{{ author.nickname }}</h3>
            <span style="margin-left: 40px">
              <el-button type="primary" size="mini" @click="subscription">{{
                subscriptionText
              }}</el-button>
            </span>
          </div>
          <span>{{ author.intro }}</span>
        </div>
      </div>
      <div class="chitchat-conatiner">
        <vue-seamless-scroll
          :data="danmulistData"
          :class-option="defaultOption"
          class="vue-seamless-scroll"
        >
          <div class="ul-scoll">
            <div
              v-for="(item, index) in danmulistData"
              class="danmu-item-container"
              :key="index"
            >
              <el-row :gutter="0" type="flex" justify="space-around">
                <el-col :lg="24" class="danmu-item-text">{{
                  item.text
                }}</el-col>
                <el-col :span="7" :offset="2" class="hidden-lg-and-down">{{
                  formateSeconds(item.time)
                }}</el-col>
              </el-row>
            </div>
          </div>
        </vue-seamless-scroll>
      </div>
      <BroadsideList
        ref="broadsideList"
        style="margin-top: 20px"
        :listSize="8"
      />
    </div>

    <el-dialog
      title="回复评论"
      :visible.sync="dialogVisible"
      width="30%"
      @close="closeInputDialog"
    >
      <el-input
        rows="5"
        type="textarea"
        placeholder="评论要有礼貌哦！"
        resize="none"
        v-model="commentContentToTop"
      >
      </el-input>
      <el-row style="margin-top: 20px" :gutter="0" type="flex" justify="center">
        <el-col :span="4" :offset="0">
          <el-button @click="dialogVisible = false">取 消</el-button>
        </el-col>
        <el-col :span="4" :offset="0">
          <el-button type="primary" @click="sendCommentToOther"
            >提 交</el-button
          >
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import DPlayer from "dplayer";
import vueSeamlessScroll from "vue-seamless-scroll";
import BroadsideList from "@/component/broadsideList.vue";
import { getById, getAuthorInfo } from "../api/videoApi";
import { getCommentByVideoId, sendComment } from "../api/commentApi";
import { isAttention, add, delect } from "../api/userSubscriptionApi";
import qs from "qs";
export default {
  components: {
    vueSeamlessScroll,
    BroadsideList,
  },
  computed: {
    subscriptionText() {
      return this.isSub ? "已关注" : " + 关注";
    },
    isLogin() {
      return sessionStorage.getItem("token") == null ? false : true;
    },
    avatar() {
      return sessionStorage.getItem("avatar") == null
        ? "http://10.24.17.72:8088/avatar.png"
        : sessionStorage.getItem("avatar");
    },
    danmulistData() {
      return this.dp ? this.dp.danmaku.dan : [];
    },
    defaultOption() {
      return {
        step: 0.2, // 数值越大速度滚动越快
        limitMoveNum: this.danmulistData.length, // 开始无缝滚动的数据量 this.danmulistData.length
        hoverStop: true, // 是否开启鼠标悬停stop
        direction: 1, // 0向下 1向上 2向左 3向右
        openWatch: true, // 开启数据实时监控刷新dom
        singleHeight: 0, // 单步运动停止的高度(默认值0是无缝不停止的滚动) direction => 0/1
        singleWidth: 0, // 单步运动停止的宽度(默认值0是无缝不停止的滚动) direction => 2/3
        waitTime: 1000, // 单步运动停止的时间(默认值1000ms)
      };
    },
  },
  data() {
    return {
      WSbaseRequest:"10.24.17.72:8080",
      baseRequest:"http://10.24.17.72:8080",
      onlineNumber: "",
      dialogVisible: false,
      author: {
        avatar: "",
        intro: "",
        nickname: "",
        userId: "",
      },
      userId: sessionStorage.getItem("id"),
      isMyDanmu: false,
      isSub: false,
      dp: null,
      videoId: "",
      authorId: "",
      videoUrl: "",
      videoTitle: "",
      videoIntro: "",
      commentContent: "",
      commentList: [],
      commentContentToTop: "",
      commentToId: null,
    };
  },
  methods: {
    openInputDailog(id) {
      this.commentToId = id;
      this.dialogVisible = true;
    },
    sendComment() {
      if (this.isLogin && this.commentContent != "") {
        sendComment(
          qs.stringify({
            userId: sessionStorage.getItem("id"),
            videoId: this.videoId,
            commentParentId: -1,
            commentContent: this.commentContent,
          })
        )
          .then((res) => {
            if (res.data.code == 200) {
              this.$message({
                message: "评论成功",
                type: "success",
              });
              this.commentContent = "";
              this.getComment();
            } else {
              this.$message({
                message: "评论失败",
                type: "error",
              });
            }
          })
          .catch((err) => {});
      } else if (!this.isLogin) {
        this.$message({
          message: "登陆后才能发表评论哦~",
          type: "error",
        });
      } else if (this.commentContent == "") {
        this.$message({
          message: "评论内容不能为空~",
          type: "error",
        });
      }
    },
    subscription() {
      if (this.isLogin) {
        if (this.isSub) {
          delect({
            fromId: sessionStorage.getItem("id"),
            toId: this.authorId,
          })
            .then((res) => {
              if (res.data.code == 200) {
                this.isSub = false;
                this.$message({
                  message: "已取消关注",
                  type: "success",
                });
              } else {
                this.$message({
                  message: "取消失败",
                  type: "error",
                });
              }
            })
            .catch((err) => {
              console.log(error);
            });
        } else {
          add(
            qs.stringify({
              fromId: this.userId,
              toId: this.authorId,
            })
          )
            .then((res) => {
              if (res.data.code == 200) {
                this.isSub = true;
                this.$message({
                  message: "关注成功~",
                  type: "success",
                });
              } else {
                this.$message({
                  message: "关注失败",
                  type: "error",
                });
              }
            })
            .catch((err) => {
              console.log(error);
            });
        }
      } else {
        this.$message({
          message: "请先登录",
          type: "error",
        });
      }
    },
    getIsAttention() {
      if (this.isLogin) {
        isAttention({
          fromId: sessionStorage.getItem("id"),
          toId: this.authorId,
        })
          .then((res) => {
            if (res.data.code == 200) {
              this.isSub = res.data.data;
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    getVideo() {
      getById(this.videoId, this.userId)
        .then((res) => {
          console.log(res);
          this.videoUrl = res.data.data.address;
          this.videoTitle = res.data.data.title;
          this.videoIntro = res.data.data.intro;
          this.authorId = res.data.data.authorId;
          this.getAuthorInfo();
          this.getIsAttention();
          const dp = new DPlayer({
            container: document.getElementById("dplayer"),
            autoplay: true,
            video: {
              url: this.videoUrl,
            },
            danmaku: {
              id: this.videoId,
              token: "Bearer " + sessionStorage.getItem("token"),
              user: sessionStorage.getItem("id"),
              maximum: 1000,
              api: this.baseRequest+"/api/danmu/getDanmu/",
              unlimited: false,
            },
          });

          this.dp = dp;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getComment() {
      getCommentByVideoId(this.videoId)
        .then((res) => {
          if (res.data.code == 200) {
            this.commentList = res.data.data.rows;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getAuthorInfo() {
      getAuthorInfo(this.authorId)
        .then((res) => {
          this.author = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //将秒换算成分钟
    formateSeconds(endTime) {
      let secondTime = parseInt(endTime); //将传入的秒的值转化为Number
      let min = 0; // 初始化分
      let h = 0; // 初始化小时
      let result = "";
      if (secondTime > 60) {
        //如果秒数大于60，将秒数转换成整数
        min = parseInt(secondTime / 60); //获取分钟，除以60取整数，得到整数分钟
        secondTime = parseInt(secondTime % 60); //获取秒数，秒数取佘，得到整数秒数
        if (min > 60) {
          //如果分钟大于60，将分钟转换成小时
          h = parseInt(min / 60); //获取小时，获取分钟除以60，得到整数小时
          min = parseInt(min % 60); //获取小时后取佘的分，获取分钟除以60取佘的分
        }
      }
      // result = `${h.toString().padStart(2, "0")}:${min
      //   .toString()
      //   .padStart(2, "0")}:${secondTime.toString().padStart(2, "0")}`;
      result = `${min.toString().padStart(2, "0")}:${secondTime
        .toString()
        .padStart(2, "0")}`;
      return result;
    },
    drawDanmu(danmu) {
      this.dp.danmaku.draw(danmu);
    },
    closeInputDialog() {
      this.commentContentToTop = "";
      this.commentToId = "";
    },
    sendCommentToOther() {
      if (this.isLogin && this.commentContentToTop != "") {
        sendComment(
          qs.stringify({
            userId: sessionStorage.getItem("id"),
            videoId: this.videoId,
            commentParentId: this.commentToId,
            commentContent: this.commentContentToTop,
          })
        )
          .then((res) => {
            if (res.data.code == 200) {
              this.$message({
                message: "评论成功",
                type: "success",
              });
              this.commentContent = "";
              this.getComment();
              this.dialogVisible = false;
            } else {
              this.$message({
                message: "评论失败",
                type: "error",
              });
            }
          })
          .catch((err) => {});
      } else if (!this.isLogin) {
        this.$message({
          message: "登陆后才能发表评论哦~",
          type: "error",
        });
      } else if (this.commentContent == "") {
        this.$message({
          message: "评论内容不能为空~",
          type: "error",
        });
      }
    },
    initWebSocket() { 
      const userID = sessionStorage.getItem("id");
      if ("WebSocket" in window) {
        console.log("您的浏览器支持WebSocket");
        const ws = new WebSocket(
          "ws://" + this.WSbaseRequest + "/ws/" + this.videoId + "/" + userID
        ); //创建WebSocket连接
        console.log(ws);
        ws.onclose = this.closeWS;
        ws.onmessage = (ev) => {
          if (ev.data.endsWith("看")) {
            const onlineNum = ev.data;
            this.onlineNumber = onlineNum;

          } else if (ev.data.toString().endsWith("}")) {
            const danOb = JSON.parse(ev.data);
            const danmu = {
              text: danOb.text,
              color: "#" + danOb.color.toString(16),
              type: "top",
            };
            this.drawDanmu(danmu);
            this.danmulistData.push(danOb);
          }
        };
      } else {
        console.log("您的浏览器不支持WebSocket");
      }
    },
    closeWS(e) {
      console.log("已端开连接");
    },
  },
  destroyed() {
    this.ws.closeWS();
    console.log(this.ws);
  },
  watch: {
    //解决路由中的参数改变，路由地址不改变页面数据不刷新问题
    $route(to, from) {
      if (to.query.id !== from.query.id) {
        this.videoId = this.$route.query.id;
        this.getVideo();
        this.commentList = [];
        this.getComment();
        this.$refs.broadsideList.getRandomVideo();
      }
    },
  },
  mounted() {
    this.videoId = this.$route.query.id;
    this.getVideo();
    this.getComment();
  },
  created() {
    this.videoId = this.$route.query.id;
    console.log(this.videoId);
    this.initWebSocket();
  },
  updated() {},
};
</script>

<style lang="scss" scoped>
.dplayer-container {
  height: 630px;
}

.video-container {
  height: 2000px;
  width: 80%;
  margin-left: 10%;

  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: start;
}

.video-container-left {
  width: 75%;
  padding-right: 10px;

  .video-info-container {
    width: 100%;
    height: 30px;
    text-align: center;
    margin-top: 5px;
    font-size: 14px;
  }
}

.video-container-right {
  width: 25%;
  display: flex;
  padding-left: 10px;
  flex-direction: column;
  align-items: flex-start;
  justify-content: start;
}

.author-container {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: start;
  margin-bottom: 22px;
}

.author-container-left {
  width: 40%;

  .author-avatar {
    width: 50px;
    height: 50px;
  }
}

.author-container-right {
  width: 60&;

  .author-container-top {
    display: flex;
    flex-direction: row;
    width: 100%;
    align-items: center;
    justify-content: space-between;
  }
}

@media screen and (max-width: 1440px) {
  .chitchat-conatiner {
    height: 415px !important;
  }
}

@media screen and (max-width: 1680px) {
  .chitchat-conatiner {
    height: 505px;
  }
}

@media screen and (max-width: 1920px) {
  .chitchat-conatiner {
    max-height: 630px;
  }
}

.chitchat-conatiner {
  width: 100%;
  max-height: 630px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: space-between;
  overflow: hidden;
  background-color: rgb(247, 241, 241);

  .ul-scoll {
    width: 100%;
    display: flex;
    font-size: 90%;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}

.danmu-item-container {
  width: 100%;
}

.vue-seamless-scroll {
  width: 100% !important;
}

.danmu-item-text {
  padding-left: 20px;
}

.send-commit-btn {
  width: 100px;
  height: 70px;
}

.comment-conatiner {
  margin-top: 20px;
}

.avatar-image {
  width: 50px;
  height: 50px;
}

.comment-list-container {
  width: 100%;
}

.commentItem-nickname {
  color: #6d757a;
  font-size: 15px;
  margin-bottom: 5px;
}

.commentItem-time {
  color: #99a2aa;
  font-size: 10px;
  margin-top: 10px;
}

.top-comment-container {
  margin: 15px 0 15px 0;
}
.onlineNum {
  font-size: 15px;
  color: #409eff;
  margin-left: 5px;
}
</style>>
